package res

import "github.com/kataras/iris"

type ExceptionsMap struct {
	Map iris.Map
}

func (m *ExceptionsMap) Set(message string, code int) iris.Map {
	m.Map = iris.Map{
		"status":  code,
		"message": message,
	}
	return m.Map
}

func ApiException(ctx iris.Context) {
	jsonMap := new(ExceptionsMap)
	switch ctx.GetStatusCode() {
	case iris.StatusNotFound:
		jsonMap.Set("页面不存在", iris.StatusNotFound)
	case iris.StatusForbidden:
		jsonMap.Set("禁止访问", iris.StatusForbidden)
	case iris.StatusBadGateway:
		jsonMap.Set("502 Bad Gateway", iris.StatusBadGateway)
	default:
		jsonMap.Set("服务器错误", iris.StatusInternalServerError)
	}
	ctx.JSON(jsonMap.Map)
}

func RenderException(ctx iris.Context) {

	if jsonOutput := ctx.URLParamExists("json"); jsonOutput {
		ApiException(ctx)
	} else {
		switch ctx.GetStatusCode() {
		case iris.StatusNotFound:
			ctx.View("errors/404.html")
		case iris.StatusForbidden:
			ctx.View("errors/403.html")
		case iris.StatusBadGateway:
			ctx.View("errors/502.html")
		default:
			ctx.View("errors/500.html")
		}
	}

}
